package com.itheima.config;

import com.alibaba.druid.pool.DruidDataSource;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.PropertySource;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;


import javax.sql.DataSource;

import java.lang.management.PlatformLoggingMXBean;
import java.sql.SQLException;


@PropertySource("classpath:db.properties")
public class JDBCConfig {
    @Value("${jdbc.username}")
    private String username;
    @Value("${jdbc.password}")
    private String password;
    @Value("${jdbc.url}")
    private String url;
    @Value("${jdbc.driverClassName}")
    private String driverClassName;




    //需要一个 DataSource对象

    //写一个方法 为了创建一个数据库连接池!!!

    /**
     * 注解的作用就是 告诉spring 这个方法 就是用来创建一个 DataSource 对象 并且放入到容器中
     * @Bean("起名字") 等同于 <bean id="名字" class="xxx类">
     * @return
     */
    @Bean
    public DataSource createDataSource(){
        DruidDataSource dataSource = new DruidDataSource();

        /*dataSource.setUsername("root");
        dataSource.setPassword("123456");
        dataSource.setUrl("jdbc:mysql://localhost:3306/xxx");
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");*/

        dataSource.setUsername(username);
        dataSource.setPassword(password);
        dataSource.setUrl(url);
        dataSource.setDriverClassName(driverClassName);


        return dataSource;
    }


    @Bean
    public PlatformTransactionManager platformTransactionManager(DataSource dataSource){
        DataSourceTransactionManager transactionManager = new DataSourceTransactionManager();
        transactionManager.setDataSource(dataSource);
        return transactionManager;

    }

    /*@Bean  //生产 MyTransactionManager 对象这个方法用来,放入spring IOC容器中 需要dataSource对象,那就从spring中取
    public  MyTransactionManager  createMyTransactionManager(DataSource dataSource) throws SQLException {

        MyTransactionManager myTransactionManager = new MyTransactionManager(dataSource);

        return   myTransactionManager;
    }*/


}
